package DAOJPA;

import java.util.List;




import film.Film;
import personne.Personne;
import DAO.DAO;
import DAO.DAOPersonne;

public class DAOPersonneJPA extends DAO implements DAOPersonne{

    static private DAOPersonneJPA instance = null;
	
	private DAOPersonneJPA() {
	}
		static public DAOPersonne getInstance() {
		 	if (instance == null)
				instance = new DAOPersonneJPA();
			 	
		 	return instance;
	}
	
	@Override
	public Personne getPersonne(int code) {
		// TODO Auto-generated method stub
		return DAO.getManager().createQuery("SELECT a FROM Personne a WHERE a.code_per = :code",Personne.class).setParameter("code", code).getSingleResult();


	}
	
	@Override
	public void deleteFromId(int code)
	{
		
		DAO.getManager().createQuery("DELETE FROM Personne a WHERE a.code_per = :code AND a.valide = :vrai" , Personne.class).setParameter("code", code).setParameter("vrai", 0).executeUpdate();
		DAO.commit();
	}
	
	@Override
	public List<Personne> getPersonnesInvalide()
	{
		return DAO.getManager().createQuery("SELECT a FROM Personne a WHERE a.valide = :vrai",Personne.class).setParameter("vrai", 1).getResultList();

	}
	

	@Override
	public List<Personne> getPersonnesValide()
	{
		return DAO.getManager().createQuery("SELECT a FROM Personne a WHERE a.valide = :vrai",Personne.class).setParameter("vrai", 0).getResultList();
	}
	
	@Override
	public List<Personne> loadAll() {
		// TODO Auto-generated method stub
		return DAO.getManager().createQuery("SELECT a FROM Personne a",Personne.class).getResultList();

	}

	@Override
	public int getNombrePersonne() {
		// TODO Auto-generated method stub
		return this.loadAll().size();
	}

	@Override
	public void save(Personne a) {
		// TODO Auto-generated method stub
		
		DAO.getManager().persist(a);
		DAO.commit();
		
	}

	@Override
	public void delete(Personne a) {
		// TODO Auto-generated method stub

		getManager().remove(a);
		DAO.commit();
	}

	
	public List<Personne> getPersonneNom(String  chaine)
	{
		return DAO.getManager().createQuery("SELECT a FROM Personne a WHERE a.valide = :vrai AND ( a.nom LIKE :chaine1 OR a.prenom LIKE :chaine2 ) ",Personne.class).setParameter("vrai", 0).setParameter("chaine1", "%"+chaine+"%").setParameter("chaine2", "%"+chaine+"%").getResultList();
	}
	
	public void updatePopularitee(int code , int popularite)
	{
		DAO.getManager().createQuery("UPDATE Personne a SET a.nbrCliques = :popularite  WHERE  a.code_per = :code AND a.valide = :vrai").setParameter("popularite", popularite).setParameter("code", code).setParameter("vrai", 0).executeUpdate();
	}
	
	
	
	
}
